package com.siss.tenancy.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author 李宜朋
 * @ClassName RemoteDownLoadFileUtil
 * @Description 远程下载文件工具类
 * @date 2020/9/9 16:06
 * @Version 2.0
 */
public class RemoteDownLoadFileUtil {

    public static File downLoadFile(String savePath,String url){
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(savePath);
        File parentFile = null;
        try
        {
            if(!f.exists()){
                f.setWritable(true,false);
                parentFile = f.getParentFile();
                if(null != parentFile && !parentFile.exists()){
                    parentFile.setWritable(true,false);
                    parentFile.mkdirs();
                }
                f.createNewFile();
            }
            urlfile = new URL(url);
            httpUrl = (HttpURLConnection)urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1)
            {
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bis.close();
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return f;
    }

    public static void main(String[] args) {
        downLoadFile("D:\\work\\wzm_workSpace\\CgIBW19YiNKAJyNDAAGJ5iV9o8M203.pdf","http://fslab.ufwl.net/group1/M00/00/4E/CgIBW19YiNKAJyNDAAGJ5iV9o8M203.pdf");
    }
}
